<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Loader;
use  app\api\controller\Job;
use app\common\service\SysLogService;

class Template extends Common
{



    public function retryFailedItems(){
        $data = request()->put();
        $id = $data['id'];
 
        $map['obtain_id'] = $id;
        $map['is_delete'] = 0;
        $map['status'] =  array("<>",1);
        $result = Db::table('zstp_obtain_queue')->where( $map)->update(['status' =>0]);
        return json(array("code" => 200, "data" => $result, "message" => "重试成功"));
    }


    public function skipTemplateNotes()
    {
        $data = request()->put();

        $map['id'] = $data['article_id'];
        $updateData["skip_template_notes"] = $data['skip_template_notes'];
        $updateData["template_skip"] = 1;
        $result = Db::table('zstp_article')->where($map)->update($updateData);
        $mapArt['template_skip'] = array("=", 0);
        $mapArt['hit_template'] = array("=", 0);

        $articleArr = Db::table('zstp_article')->where($mapArt)->order(array("id" => "asc"))->find();

        return json(array("code" => 200, "data" => $articleArr['id'], "message" => "标记成功"));
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function getTemplateList()
    {

        $data = request()->put();
        $length = $data['limit'];
        //$page = 2;
        if (empty($data['page'])) {
            $page = 0;
        } else {
            $page = $data['page'] - 1;
        }
        $offset = $page * $length;
        $map = array();

        $map['is_delete'] = 0;

        $result = Db::table('zstp_template')->where($map)->field("*")->limit($offset, $length)->order(array("create_time" => "desc"))->select();
        $totalCount = Db::table('zstp_template')->where($map)->count();
        return json(array(
            "code" => 200,
            "data" => array("resultList" => $result),
            "totalCount" => $totalCount,
        ));
    }

    public function delTemplateById()
    {

        $data = request()->put();
        $map['id'] = $data['id'];
        $data['is_delete'] = 1;
        $result = Db::table('zstp_template')->where($map)->update($data);

        if ($result) {
            $sysLogService = new SysLogService();
            $templateName = Db::table('zstp_template')->where('id', $data['id'])->value('template_name');
            $result =  $sysLogService->addLog('删除模板id('.$templateName.')', $data['id'], 3, '删除模板id:'.$data['id']);
            return json(array("code" => 200, "data" => $result, "message" => "删除成功"));
        } else {
            return json(array("code" => 400, "data" => $result, "message" => "删除失败"));
        }
    }

    public function saveOrUptTemplate()
    {

        $data = request()->put();


        $id = $data['id'];

        $list = array();
        $list['is_delete'] = 0;
        $template_name = $data['template_name'];
        $priority = $data['priority'];
        $mode = $data['mode'];
        $status = $data['status'];

        // 检验 identifying_features

        $identifyingFeaturesData = $data['identifying_features'];

        if (empty($identifyingFeaturesData)) {
            return json(array("code" => 400, "data" => array(), "message" => "identifying_features不能为空"));
        }

        foreach ($identifyingFeaturesData as $key => $value) {
            if (empty($value)) {
                return json(array("code" => 400, "data" => array(), "message" => "判定特征有数据未填写"));
            }
            $fordata = $value['value'];
            foreach ($fordata as $k => $v) {
                if (empty($v['titleOrContent'])) {
                    return json(array("code" => 400, "data" => array(), "message" => "标题或者内容未填写"));
                }
                if (empty($v['value'])) {
                    return json(array("code" => 400, "data" => array(), "message" => "正则未填写"));
                }
            }
        }


        $list['template_name'] = $template_name;
        $list['priority'] = $priority;
        $list['mode'] = $mode;
        $list['status'] = $status;
        $list['identifying_features'] = json_encode($identifyingFeaturesData, JSON_UNESCAPED_UNICODE);
        $list['article_id'] = $data['article_id'];


        if (empty($id)) {
            // 添加
            $list['create_time'] = date("Y-m-d H:i:s");
            $result = Db::table("zstp_template")->insert($list);
            if ($result) {
                return json(array("code" => 200, "data" => $result, "message" => "添加成功"));
            } else {
                return json(array("code" => 400, "data" => $result, "message" => "添加失败"));
            }
        } else {
            //更新
            $list['update_time'] = date("Y-m-d H:i:s");
            $result = Db::table("zstp_template")->where(array("id" => $id))->update($list);

            return json(array("code" => 200, "data" => $result, "message" => "保存成功"));
        }
    }

    public function saveOrUptTemplateFind()
    {

        $data = request()->put();

        if (empty($data['id'])) {
            $id = null;
        } else {
            $id = $data['id'];
        }


        $list = array();
        $list['is_delete'] = 0;
        $template_name = $data['template_name'];
        $priority = $data['priority'];
        $mode = $data['mode'];
        $status = $data['status'];

        // 检验 identifying_features

        $identifyingFeaturesData = $data['identifying_features'];

        if (empty($identifyingFeaturesData)) {
            return json(array("code" => 400, "data" => array(), "message" => "identifying_features不能为空"));
        }

        foreach ($identifyingFeaturesData as $key => $value) {
            if (empty($value)) {
                return json(array("code" => 400, "data" => array(), "message" => "判定特征有数据未填写"));
            }
            $fordata = $value['value'];
            foreach ($fordata as $k => $v) {
                if (empty($v['titleOrContent'])) {
                    return json(array("code" => 400, "data" => array(), "message" => "标题或者内容未填写"));
                }
                if (empty($v['value'])) {
                    return json(array("code" => 400, "data" => array(), "message" => "正则未填写"));
                }
            }
        }


        $list['template_name'] = $template_name;
        $list['priority'] = $priority;
        $list['mode'] = $mode;
        $list['status'] = $status;
        $list['identifying_features'] = json_encode($identifyingFeaturesData, JSON_UNESCAPED_UNICODE);
        $list['article_id'] = $data['article_id'];


        if (empty($id)) {
            // 添加
            $list['create_time'] = date("Y-m-d H:i:s");
            $id = Db::table("zstp_template")->insertGetId($list);
        } else {
            //更新
            $list['update_time'] = date("Y-m-d H:i:s");
            $result = Db::table("zstp_template")->where(array("id" => $id))->update($list);
        }


        // 跑程序

        $Job = new Job();

        $templateArr = Db::table('zstp_template')->where(array("id" => $id))->select();


        $map = array();

        //        $mapArt['id'] = array("egt", $data['article_id']);

        $mapArt['template_skip'] = array("=", 0);
        //没有命中模版
        $mapArt['hit_template'] = array("=", 0);

        $articleArr = Db::table('zstp_article')->where($mapArt)->order(array("id" => "asc"))->select();


        if (empty($articleArr)) {
            return json(array("code" => 400, "data" => $articleArr, "message" => "文章已经跑完"));
        }

        $mun = 0;


        foreach ($articleArr as $key => $value) {
            $data = $Job->forTemplateArr($templateArr, $value);
            if ($data['code'] == 200) {
                $dataUpdate = array();
                $dataUpdate['hit_template'] = $id;
                Db::table('zstp_article')->where(array("id" => $value['id']))->update($dataUpdate);
                $mun = $mun + 1;
            }
        }

        if ($mun == 0) {
            return json(array("code" => 400, "data" => $value['id'], "message" => "没有匹配到数据"));
        } else {
            $articleArr = Db::table('zstp_article')->where($mapArt)->order(array("id" => "asc"))->find();

            return json(array("code" => 200, "data" => $articleArr['id'], "message" => "匹配到{$mun}文章"));
        }
    }


    public function getTemplateById()
    {
        $data = request()->put();

        if (empty($data['id'])) {
            return json(array("code" => 400, "data" => array(), "message" => "没有数据"));
        }
        $id = $data['id'];

        $result = Db::table("zstp_template")->where(array("id" => $id))->find();

        $result['identifying_features'] = json_decode($result['identifying_features'], true);

        return json(array("code" => 200, "data" => $result, "message" => "删除成功"));
    }

    public function getAllTemplate()
    {
        $map['is_delete'] = 0;
        $map['mode'] = 1;
        $result = Db::table('zstp_template')->where($map)->field("id,template_name")->select();
        return json(array("code" => 200, "data" => $result));
    }

    public function getObtainList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $name = input('name/s', '');
        $qzh = input('qzh/s', '');
        $status = input('status');



        $where = ['is_delete' => '0'];

        if ($name !== '') {
            $where['name'] = ['like', "%{$name}%"];
        }
        if ($qzh !== '') {
            $where['qzh'] = ['like', "%{$qzh}%"];
        }
        if ($status !== '' && $status !== null) {
            $where['status'] = $status;
        }



        $total = db('zstp_obtain')->where($where)->count();
        $list = db('zstp_obtain')
            ->where($where)
            ->page($page, $limit)
            ->order('id desc')
            ->select();


        foreach ($list as $key => $value) {
            // 查进度
          //查任务一共几篇
           $mapResult['obtain_id'] = $value['id'];
           $mapResult['is_delete'] = 0;
           $countq = Db::table('zstp_obtain_queue')
           ->where($mapResult)
           ->count();
        

           $mapResult['status'] = 1;
           $countResult = Db::table('zstp_obtain_queue')
           ->where($mapResult)
           ->count();

           if($countq == 0){
            $list[$key]['progress'] = 0;
           }else{
            $progress = $countResult/$countq*100;
            $list[$key]['progress'] = round($progress,2);
           } 
        }

        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => ['resultList' => $list],
            'totalCount' => $total
        ]);
    }

    /**
     * 添加任务
     */
    public function addObtain()
    {
        $data = [
            'name' => input('name/s', ''),
            'qzh' => input('qzh/s', ''),
            'ollama_url' => input('ollama_url/s', ''),
            'limit' => input('limit/d', 0),
            'status' => 0,
            'lbh' => input('lbh/s', ''),
            'create_time' => date('Y-m-d H:i:s'),
            'is_delete' => '0'
        ];

        // 验证必填字段
        if (empty($data['name'])  || empty($data['ollama_url'])) {
            return json(['code' => 400, 'message' => '请填写完整信息']);
        }

        // 开启事务
        Db::startTrans();
        try {
            // 插入任务并获取ID
            $obtain_id = Db::table('zstp_obtain')->insertGetId($data);

            // 构建查询条件
            $mapSx = [];
            if (!empty($data['qzh'])) {
                $mapSx['qzh'] = $data['qzh'];
            }
            if (!empty($data['lbh'])) {
                $mapSx['lbh'] = $data['lbh'];
            }

            // 计算符合条件的总记录数
            $totalCount = Db::table("zstp_article")->where($mapSx)->count();

            if ($totalCount == 0) {
                Db::rollback();
                return json(['code' => 400, 'message' => '没有符合条件的数据']);
            }

            // 设置每批处理的数量
            $batchSize = 10;
            $processedCount = 0;

            // 计算总批次数
            $totalBatches = ceil($totalCount / $batchSize);

            for ($batch = 0; $batch < $totalBatches; $batch++) {
                // 计算当前批次的偏移量
                $offset = $batch * $batchSize;

                // 获取当前批次的数据
                $query = Db::table("zstp_article")
                    ->field("id, dh, tm")  // 只查询需要的字段
                    ->where($mapSx)
                    ->order('id desc')
                    ->limit($offset, $batchSize);

                // 如果设置了任务限制，且当前已处理数量+当前批次大小超过限制，则调整批次大小
                if ($data['limit'] > 0 && ($processedCount + $batchSize) > $data['limit']) {
                    $remainingLimit = $data['limit'] - $processedCount;
                    if ($remainingLimit <= 0) {
                        break; // 已达到限制，停止处理
                    }
                    $query = $query->limit($offset, $remainingLimit);
                }

                $list = $query->select();

            
            // var_dump( $query->getLastsql() );

                if (empty($list)) {
                    continue; // 当前批次没有数据，继续下一批
                }

                // 构建批量插入数据
                $insertAdd = [];
                foreach ($list as $value) {
                    $insert = [
                        'obtain_id' => $obtain_id,
                        'article_id' => $value['id'],
                        'create_time' => date('Y-m-d H:i:s'),
                        'tm' => $value['tm'] ?? '',
                        'dh' => $value['dh'] ?? ''
                    ];
                    $insertAdd[] = $insert;
                }

                // 批量插入当前批次数据
                if (!empty($insertAdd)) {
                    Db::table("zstp_obtain_queue")->insertAll($insertAdd);
                    $processedCount += count($insertAdd);
                }

                // 如果设置了限制且已达到限制，则停止处理
                if ($data['limit'] > 0 && $processedCount >= $data['limit']) {
                    break;
                }
            }

            // 提交事务
            Db::commit();

            return json([
                'code' => 200,
                'message' => "添加成功，共处理{$processedCount}条数据",
                'data' => ['obtain_id' => $obtain_id]
            ]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json([
                'code' => 500,
                'message' => '添加失败: ' . $e->getMessage()
            ]);
        }

        return json(['code' => 200, 'message' => '添加成功']);
    }

    /**
     * 更新任务
     */
    public function updateObtain()
    {
        $id = input('id/d', 0);
        if (!$id) {
            return json(['code' => 400, 'message' => '参数错误']);
        }

        $data = [
            'name' => input('name/s', ''),
            'qzh' => input('qzh/s', ''),
            'ollama_url' => input('ollama_url/s', ''),
            'limit' => input('limit/d', 0)
        ];

        // 验证必填字段
        if (empty($data['name']) || empty($data['qzh']) || empty($data['ollama_url'])) {
            return json(['code' => 400, 'message' => '请填写完整信息']);
        }

        $result = db('zstp_obtain')->where('id', $id)->update($data);
        if ($result !== false) {
            return json(['code' => 200, 'message' => '更新成功']);
        }
        return json(['code' => 400, 'message' => '更新失败']);
    }

    /**
     * 删除任务
     */
    public function deleteObtain()
    {
        $id = input('id/d', 0);
        if (!$id) {
            return json(['code' => 400, 'message' => '参数错误']);
        }

        $result = db('zstp_obtain')->where('id', $id)->update(['is_delete' => '1']);

        Db::table('zstp_obtain_queue')->where('obtain_id', $id)->update(['is_delete' => '1']);
        
        if ($result) {
            $sysLogService = new SysLogService();
            $name = Db::table('zstp_obtain')->where('id', $id)->value('name');
            $result =  $sysLogService->addLog('删除任务('.$name.')', $id, 3, '任务id:'.$id);


            return json(['code' => 200, 'message' => '删除成功']);
        }
        return json(['code' => 400, 'message' => '删除失败']);
    }

    /**
     * 启动任务
     */
    public function startObtain()
    {
        $id = input('id/d', 0);
        if (!$id) {
            return json(['code' => 400, 'message' => '参数错误']);
        }

        // 检查任务是否存在且未删除
        $task = db('zstp_obtain')->where(['id' => $id, 'is_delete' => '0'])->find();
        if (!$task) {
            return json(['code' => 400, 'message' => '任务不存在']);
        }

        // 检查任务状态
        if ($task['status'] == 1) {
            return json(['code' => 400, 'message' => '任务已经在运行中']);
        }

        $result = db('zstp_obtain')->where('id', $id)->update(['status' => 1]);
        if ($result) {
            // TODO: 这里可以添加实际启动任务的逻辑
            return json(['code' => 200, 'message' => '启动成功']);
        }
        return json(['code' => 400, 'message' => '启动失败']);
    }

    /**
     * 停止任务
     */
    public function stopObtain()
    {
        $id = input('id/d', 0);
        if (!$id) {
            return json(['code' => 400, 'message' => '参数错误']);
        }

        // 检查任务是否存在且未删除
        $task = db('zstp_obtain')->where(['id' => $id, 'is_delete' => '0'])->find();
        if (!$task) {
            return json(['code' => 400, 'message' => '任务不存在']);
        }

        // 检查任务状态
        if ($task['status'] == 0) {
            return json(['code' => 400, 'message' => '任务已经停止']);
        }

        $result = db('zstp_obtain')->where('id', $id)->update(['status' => 0]);
        if ($result) {
            // TODO: 这里可以添加实际停止任务的逻辑
            return json(['code' => 200, 'message' => '停止成功']);
        }
        return json(['code' => 400, 'message' => '停止失败']);
    }





    /**
     * 获取队列列表
     * 支持分页、状态筛选、任务ID筛选
     */
    public function getQueueList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $status = input('status');
        $obtain_id = input('obtain_id/d');
        $tm = input('tm/s', '');
        $dh = input('dh/s', '');

        // 构建查询条件
        $where = ['q.is_delete' => '0'];

        if ($status !== '' && $status !== null) {
            $where['q.status'] = $status;
        }

        if ($obtain_id) {
            $where['q.obtain_id'] = $obtain_id;
        }

        if ($tm) {
            $where['q.tm'] = ['like', "%{$tm}%"];
        }

        if ($dh) {
            $where['q.dh'] = ['like', "%{$dh}%"];
        }

        // 查询总数
        $total = Db::table('zstp_obtain_queue')
            ->alias('q')
            ->where($where)
            ->count();

        // 查询列表数据
        $list = Db::table('zstp_obtain_queue')
            ->alias('q')
            ->field('q.*, o.name as obtain_name, o.qzh, o.ollama_url')
            ->join('zstp_obtain o', 'q.obtain_id = o.id', 'LEFT')
            ->where($where)
            ->order('q.id desc')
            ->page($page, $limit)
            ->select();

        // 状态描述映射
        $statusMap = [
            0 => '待处理',
            1 => '处理中',
            2 => '处理完成',
            3 => '处理失败'
        ];

        // 格式化数据
        foreach ($list as &$item) {
            $item['status_text'] = isset($statusMap[$item['status']]) ? $statusMap[$item['status']] : '未知状态';
            // 处理时间显示
            if ($item['create_time']) {
                $item['create_time'] = date('Y-m-d H:i:s', strtotime($item['create_time']));
            }
            if ($item['update_time']) {
                $item['update_time'] = date('Y-m-d H:i:s', strtotime($item['update_time']));
            }
        }

        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => [
                'resultList' => $list,
                'statusMap' => $statusMap
            ],
            'totalCount' => $total
        ]);
    }


    function getOllamaUrls()
    {
        $list = Db::table('zstp_ollama')->select();

        $map['status'] = array("=", 1);
        $map['is_delete'] = array("=", 0);

        $ollamaList =  Db::table('zstp_obtain')->field('id,ollama_url')->where($map)->select();



        $ollamaUrlList = array_column($ollamaList, 'ollama_url');


        foreach ($list as  $key => $item) {

            if (in_array($item['ip'], $ollamaUrlList)) {


                unset($list[$key]);
                continue;
            }
        }

        $list = array_values($list);






        return json(['code' => 200, 'message' => '获取成功', 'data' => $list]);
    }



    function getpersonalattributes()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $name = input('name/s', '');
        $gender = input('gender/s', '');
        $ethnicity = input('ethnicity/s', '');
        $political_status = input('political_status/s', '');
        $article_id = input('article_id/d', '');

        $where = ['a.is_delete' => '0'];

        if ($name !== '') {
            $where['a.name'] = ['like', "%{$name}%"];
        }
        if ($article_id !== '') {
            $where['a.article_id'] = $article_id;
        }

        $total = Db::table('zstp_neo4j_personal_attributes')
            ->alias('a')
            ->where($where)
            ->count();

        $list = Db::table('zstp_neo4j_personal_attributes')
            ->alias('a')
            ->field([
                'a.*',
                'art.dh'
            ])
            ->join('zstp_article art', 'a.article_id = art.id', 'LEFT')
            ->where($where)
            ->page($page, $limit)
            ->order('a.id desc')
            ->select();

        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => ['resultList' => $list],
            'totalCount' => $total
        ]);
    }


    function deletepersonalattribute()
    {
        $id = input('id/d', 0);
        if (!$id) {
            return json(['code' => 400, 'message' => '参数错误']);
        }

        // 检查记录是否存在
        $record = db('zstp_neo4j_personal_attributes')->where('id', $id)->find();
        if (!$record) {
            return json(['code' => 400, 'message' => '记录不存在']);
        }

        // 执行逻辑删除
        $result = db('zstp_neo4j_personal_attributes')
            ->where('id', $id)
            ->update([
                'is_delete' => '1',
                'update_time' => date('Y-m-d H:i:s')
            ]);

        if ($result) {
            $sysLogService = new SysLogService();
            $tm = Db::table('zstp_neo4j_personal_attributes')->where('id', $id)->value('name');
            $result =  $sysLogService->addLog('删除人物属性('.$tm.')', $id, 3, '个人属性id:'.$id);
            return json(['code' => 200, 'message' => '删除成功']);
        }
        return json(['code' => 400, 'message' => '删除失败']);
    }

    function getorganizationlist()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $unit_name = input('unit_name/s', '');
        $unit_designation = input('unit_designation/s', '');
        $unit_type = input('unit_type/s', '');
        $location = input('location/s', '');
        $article_id = input('article_id/d', '');

        $where = ['is_delete' => '0'];

        if ($unit_name !== '') {
            $where['unit_name'] = ['like', "%{$unit_name}%"];
        }
        if ($unit_designation !== '') {
            $where['unit_designation'] = ['like', "%{$unit_designation}%"];
        }
        if ($unit_type !== '') {
            $where['unit_type'] = ['like', "%{$unit_type}%"];
        }
        if ($location !== '') {
            $where['location'] = ['like', "%{$location}%"];
        }
        if ($article_id !== '') {
            $where['article_id'] = $article_id;
        }

        $total = Db::table('zstp_neo4j_organization')
            ->where($where)
            ->count();

        $list = Db::table('zstp_neo4j_organization')

            ->where($where)
            ->page($page, $limit)
            ->order('id desc')
            ->select();

        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => ['resultList' => $list],
            'totalCount' => $total
        ]);
    }


    function getSignificantEventsList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $unit_name = input('unit_name/s', '');
        $event_title = input('event_title/s', '');
        $type = input('type/s', '');
        $location = input('location/s', '');
        $event_date_start = input('event_date_start/s', '');
        $event_date_end = input('event_date_end/s', '');
        $article_id = input('article_id/d', '');

        $where = ['is_delete' => '0'];

        if ($unit_name !== '') {
            $where['unit_name'] = ['like', "%{$unit_name}%"];
        }
        if ($event_title !== '') {
            $where['event_title'] = ['like', "%{$event_title}%"];
        }
        if ($type !== '') {
            $where['type'] = ['like', "%{$type}%"];
        }
        if ($location !== '') {
            $where['location'] = ['like', "%{$location}%"];
        }
        if ($article_id !== '') {
            $where['article_id'] = $article_id;
        }

        // 日期范围查询
        if ($event_date_start !== '' && $event_date_end !== '') {
            $where['event_date'] = ['between', [$event_date_start, $event_date_end]];
        } else if ($event_date_start !== '') {
            $where['event_date'] = ['>=', $event_date_start];
        } else if ($event_date_end !== '') {
            $where['event_date'] = ['<=', $event_date_end];
        }

        $total = Db::table('zstp_neo4j_significant_events')
         
            ->where($where)
            ->count();

        $list = Db::table('zstp_neo4j_significant_events')
          
            ->where($where)
            ->page($page, $limit)
            ->order('event_date desc, id desc')
            ->select();

        // 格式化日期显示
        foreach ($list as &$item) {
            if (!empty($item['event_date'])) {
                $item['event_date'] = date('Y-m-d', strtotime($item['event_date']));
            }
            if (!empty($item['create_time'])) {
                $item['create_time'] = date('Y-m-d H:i:s', strtotime($item['create_time']));
            }
            if (!empty($item['update_time'])) {
                $item['update_time'] = date('Y-m-d H:i:s', strtotime($item['update_time']));
            }
        }

        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => ['resultList' => $list],
            'totalCount' => $total
        ]);
    }

    function getSocialRelationsList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $name = input('name/s', '');
        $linked_person_name = input('linked_person_name/s', '');
        $relationship_type = input('relationship_type/s', '');
        $gender = input('gender/s', '');
        $political_status = input('political_status/s', '');
        $workplace = input('workplace/s', '');
        $article_id = input('article_id/d', '');

        $where = ['is_delete' => '0'];

        if ($name !== '') {
            $where['name'] = ['like', "%{$name}%"];
        }
        if ($linked_person_name !== '') {
            $where['linked_person_name'] = ['like', "%{$linked_person_name}%"];
        }
        if ($relationship_type !== '') {
            $where['relationship_type'] = ['like', "%{$relationship_type}%"];
        }
        if ($gender !== '') {
            $where['gender'] = $gender;
        }
        if ($political_status !== '') {
            $where['political_status'] = ['like', "%{$political_status}%"];
        }
        if ($workplace !== '') {
            $where['workplace'] = ['like', "%{$workplace}%"];
        }
        if ($article_id !== '') {
            $where['article_id'] = $article_id;
        }


        //社会关系

        $where['relationship_type'] = array(  "not in",array("女儿","儿子","配偶","本人"));

        $total = Db::table('zstp_neo4j_social_relations')
            ->where($where)
            ->count();

        $list = Db::table('zstp_neo4j_social_relations')

            ->where($where)
            ->page($page, $limit)
            ->order('id desc')
            ->select();

        // 格式化日期显示
        foreach ($list as &$item) {
            if (!empty($item['birth_date'])) {
                $item['birth_date'] = date('Y-m-d', strtotime($item['birth_date']));
            }
            if (!empty($item['create_time'])) {
                $item['create_time'] = date('Y-m-d H:i:s', strtotime($item['create_time']));
            }
            if (!empty($item['update_time'])) {
                $item['update_time'] = date('Y-m-d H:i:s', strtotime($item['update_time']));
            }
        }

        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => ['resultList' => $list],
            'totalCount' => $total
        ]);
    }

    function getEventList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $personnel_name = input('personnel_name/s', '');
        $event_type = input('event_type/s', '');
        $issuer = input('issuer/s', '');
        $event_date_start = input('event_date_start/s', '');
        $event_date_end = input('event_date_end/s', '');
        $article_id = input('article_id/d', '');

        $where = ['is_delete' => '0'];

        if ($personnel_name !== '') {
            $where['personnel_name'] = ['like', "%{$personnel_name}%"];
        }
        if ($event_type !== '') {
            $where['event_type'] = ['like', "%{$event_type}%"];
        }
        if ($issuer !== '') {
            $where['issuer'] = ['like', "%{$issuer}%"];
        }
        if ($article_id !== '') {
            $where['article_id'] = $article_id;
        }

        // 日期范围查询
        if ($event_date_start !== '' && $event_date_end !== '') {
            $where['event_date'] = ['between', [$event_date_start, $event_date_end]];
        } else if ($event_date_start !== '') {
            $where['event_date'] = ['>=', $event_date_start];
        } else if ($event_date_end !== '') {
            $where['event_date'] = ['<=', $event_date_end];
        }

        $total = db('zstp_neo4j_event')->where($where)->count();
        $list = db('zstp_neo4j_event')
            ->where($where)
            ->page($page, $limit)
            ->order('event_date desc, id desc')
            ->select();

        // 格式化日期显示
        foreach ($list as &$item) {
            if (!empty($item['event_date'])) {
                $item['event_date'] = date('Y-m-d', strtotime($item['event_date']));
            }
            if (!empty($item['create_time'])) {
                $item['create_time'] = date('Y-m-d H:i:s', strtotime($item['create_time']));
            }
            if (!empty($item['update_time'])) {
                $item['update_time'] = date('Y-m-d H:i:s', strtotime($item['update_time']));
            }
        }

        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => ['resultList' => $list],
            'totalCount' => $total
        ]);
    }


    function getHistoricalEvolutionList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $unit_name = input('unit_name/s', '');
        $change_type = input('change_type/s', '');
        $commander_name = input('commander_name/s', '');
        $change_date_start = input('change_date_start/s', '');
        $change_date_end = input('change_date_end/s', '');
        $article_id = input('article_id/d', '');

        $where = ['is_delete' => '0'];

        if ($unit_name !== '') {
            $where['unit_name'] = ['like', "%{$unit_name}%"];
        }
        if ($change_type !== '') {
            $where['change_type'] = ['like', "%{$change_type}%"];
        }
        if ($commander_name !== '') {
            $where['commander_name'] = ['like', "%{$commander_name}%"];
        }
        if ($article_id !== '') {
            $where['article_id'] = $article_id;
        }

        // 日期范围查询
        if ($change_date_start !== '' && $change_date_end !== '') {
            $where['change_date'] = ['between', [$change_date_start, $change_date_end]];
        } else if ($change_date_start !== '') {
            $where['change_date'] = ['>=', $change_date_start];
        } else if ($change_date_end !== '') {
            $where['change_date'] = ['<=', $change_date_end];
        }

        $total = Db::table('zstp_neo4j_historical_evolution')
            ->where($where)
            ->count();

        $list = Db::table('zstp_neo4j_historical_evolution')
            ->where($where)
            ->page($page, $limit)
            ->order('change_date desc, id desc')
            ->select();

        // 格式化日期显示
        foreach ($list as &$item) {
            if (!empty($item['change_date'])) {
                $item['change_date'] = date('Y-m-d', strtotime($item['change_date']));
            }
            if (!empty($item['create_time'])) {
                $item['create_time'] = date('Y-m-d H:i:s', strtotime($item['create_time']));
            }
            if (!empty($item['update_time'])) {
                $item['update_time'] = date('Y-m-d H:i:s', strtotime($item['update_time']));
            }
        }

        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => ['resultList' => $list],
            'totalCount' => $total
        ]);
    }

    function getRewardsPunishmentsList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $event_type = input('event_type/s', '');
        $subject_name = input('subject_name/s', '');
        $issuer = input('issuer/s', '');
        $event_date_start = input('event_date_start/s', '');
        $event_date_end = input('event_date_end/s', '');
        $article_id = input('article_id/d', '');

        $where = ['is_delete' => '0'];

        if ($event_type !== '') {
            $where['event_type'] = ['like', "%{$event_type}%"];
        }
        if ($subject_name !== '') {
            $where['subject_name'] = ['like', "%{$subject_name}%"];
        }
        if ($issuer !== '') {
            $where['issuer'] = ['like', "%{$issuer}%"];
        }
        if ($article_id !== '') {
            $where['article_id'] = $article_id;
        }

        // 日期范围查询
        if ($event_date_start !== '' && $event_date_end !== '') {
            $where['event_date'] = ['between', [$event_date_start, $event_date_end]];
        } else if ($event_date_start !== '') {
            $where['event_date'] = ['>=', $event_date_start];
        } else if ($event_date_end !== '') {
            $where['event_date'] = ['<=', $event_date_end];
        }

        $total = db('zstp_neo4j_rewards_punishments_event')->alias('a')->where($where)->count();
        $list = db('zstp_neo4j_rewards_punishments_event')
            ->where($where)
            ->page($page, $limit)
            ->order('event_date desc, id desc')
            ->select();


        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => ['resultList' => $list],
            'totalCount' => $total
        ]);
    }

    function getPositionEventList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $event_type = input('event_type/s', '');
        $personnel_name = input('personnel_name/s', '');
        $department = input('department/s', '');
        $issuer = input('issuer/s', '');
        $event_date_start = input('event_date_start/s', '');
        $event_date_end = input('event_date_end/s', '');
        $article_id = input('article_id/d', '');

        $where = ['is_delete' => '0'];

        if ($event_type !== '') {
            $where['event_type'] = ['like', "%{$event_type}%"];
        }
        if ($personnel_name !== '') {
            $where['personnel_name'] = ['like', "%{$personnel_name}%"];
        }
        if ($department !== '') {
            $where['department'] = ['like', "%{$department}%"];
        }
        if ($issuer !== '') {
            $where['issuer'] = ['like', "%{$issuer}%"];
        }
        if ($article_id !== '') {
            $where['a.article_id'] = $article_id;
        }

        // 日期范围查询
        if ($event_date_start !== '' && $event_date_end !== '') {
            $where['event_date'] = ['between', [$event_date_start, $event_date_end]];
        } else if ($event_date_start !== '') {
            $where['event_date'] = ['>=', $event_date_start];
        } else if ($event_date_end !== '') {
            $where['event_date'] = ['<=', $event_date_end];
        }

        $total = db('zstp_neo4j_position_event')
        ->where($where)
        ->count();
        $list = db('zstp_neo4j_position_event')

            ->where($where)
            ->page($page, $limit)
            ->order('event_date desc, id desc')
            ->select();

        // 格式化日期显示
        foreach ($list as &$item) {
            if (!empty($item['event_date'])) {
                $item['event_date'] = date('Y-m-d', strtotime($item['event_date']));
            }
            if (!empty($item['effective_date'])) {
                $item['effective_date'] = date('Y-m-d', strtotime($item['effective_date']));
            }
            if (!empty($item['create_time'])) {
                $item['create_time'] = date('Y-m-d H:i:s', strtotime($item['create_time']));
            }
            if (!empty($item['update_time'])) {
                $item['update_time'] = date('Y-m-d H:i:s', strtotime($item['update_time']));
            }

            // 添加职位变动描述
            $item['position_change'] = '';
            if (!empty($item['original_position']) && !empty($item['current_position'])) {
                $item['position_change'] = "从 {$item['original_position']} 调任为 {$item['current_position']}";
            } else if (empty($item['original_position']) && !empty($item['current_position'])) {
                $item['position_change'] = "任命为 {$item['current_position']}";
            } else if (!empty($item['original_position']) && empty($item['current_position'])) {
                $item['position_change'] = "原任 {$item['original_position']}";
            }
        }

        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => ['resultList' => $list],
            'totalCount' => $total
        ]);
    }

    function getRankEventList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $event_type = input('event_type/s', '');
        $personnel_name = input('personnel_name/s', '');
        $department = input('department/s', '');
        $issuer = input('issuer/s', '');
        $event_date_start = input('event_date_start/s', '');
        $event_date_end = input('event_date_end/s', '');
        $article_id = input('article_id/d', '');

        $where = ['is_delete' => '0'];

        if ($event_type !== '') {
            $where['event_type'] = ['like', "%{$event_type}%"];
        }
        if ($personnel_name !== '') {
            $where['personnel_name'] = ['like', "%{$personnel_name}%"];
        }
        if ($department !== '') {
            $where['department'] = ['like', "%{$department}%"];
        }
        if ($issuer !== '') {
            $where['issuer'] = ['like', "%{$issuer}%"];
        }
        if ($article_id !== '') {
            $where['article_id'] = $article_id;
        }

        // 日期范围查询
        if ($event_date_start !== '' && $event_date_end !== '') {
            $where['event_date'] = ['between', [$event_date_start, $event_date_end]];
        } else if ($event_date_start !== '') {
            $where['event_date'] = ['>=', $event_date_start];
        } else if ($event_date_end !== '') {
            $where['event_date'] = ['<=', $event_date_end];
        }

        $total = db('zstp_neo4j_rank_event')

        ->where($where)
        ->count();
        $list = db('zstp_neo4j_rank_event')

            ->where($where)
            ->page($page, $limit)
            ->order('event_date desc, id desc')
            ->select();

        // 格式化日期显示
        foreach ($list as &$item) {
            if (!empty($item['event_date'])) {
                $item['event_date'] = date('Y-m-d', strtotime($item['event_date']));
            }
            if (!empty($item['effective_date'])) {
                $item['effective_date'] = date('Y-m-d', strtotime($item['effective_date']));
            }
            if (!empty($item['create_time'])) {
                $item['create_time'] = date('Y-m-d H:i:s', strtotime($item['create_time']));
            }
            if (!empty($item['update_time'])) {
                $item['update_time'] = date('Y-m-d H:i:s', strtotime($item['update_time']));
            }

        }

        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => ['resultList' => $list],
            'totalCount' => $total
        ]);
    }

    function getAbroadEventList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $event_type = input('event_type/s', '');
        $personnel_name = input('personnel_name/s', '');
        $country = input('country/s', '');
        $abroad_date_start = input('abroad_date_start/s', '');
        $abroad_date_end = input('abroad_date_end/s', '');
        $return_date_start = input('return_date_start/s', '');
        $return_date_end = input('return_date_end/s', '');
        $article_id = input('article_id/d', '');

        $where = ['is_delete' => '0'];

        if ($event_type !== '') {
            $where['event_type'] = ['like', "%{$event_type}%"];
        }
        if ($personnel_name !== '') {
            $where['personnel_name'] = ['like', "%{$personnel_name}%"];
        }
        if ($country !== '') {
            $where['country'] = ['like', "%{$country}%"];
        }
        if ($article_id !== '') {
            $where['article_id'] = $article_id;
        }

        // 出国日期范围查询
        if ($abroad_date_start !== '' && $abroad_date_end !== '') {
            $where['abroad_date'] = ['between', [$abroad_date_start, $abroad_date_end]];
        } else if ($abroad_date_start !== '') {
            $where['abroad_date'] = ['>=', $abroad_date_start];
        } else if ($abroad_date_end !== '') {
            $where['abroad_date'] = ['<=', $abroad_date_end];
        }

        // 归国日期范围查询
        if ($return_date_start !== '' && $return_date_end !== '') {
            $where['return_date'] = ['between', [$return_date_start, $return_date_end]];
        } else if ($return_date_start !== '') {
            $where['return_date'] = ['>=', $return_date_start];
        } else if ($return_date_end !== '') {
            $where['return_date'] = ['<=', $return_date_end];
        }

        // 使用子查询先获取总数，避免 JOIN 后再 COUNT 的性能问题
        $total = Db::table('zstp_neo4j_abroad_event')

            ->where($where)
            ->count();

        // 主查询使用 LEFT JOIN
        $list = Db::table('zstp_neo4j_abroad_event')

            ->where($where)
            ->page($page, $limit)
            ->order('abroad_date desc, id desc')
            ->select();

        // 格式化日期显示
        foreach ($list as &$item) {
            if (!empty($item['abroad_date'])) {
                $item['abroad_date'] = date('Y-m-d', strtotime($item['abroad_date']));
            }
            if (!empty($item['return_date'])) {
                $item['return_date'] = date('Y-m-d', strtotime($item['return_date']));
            }
            if (!empty($item['create_time'])) {
                $item['create_time'] = date('Y-m-d H:i:s', strtotime($item['create_time']));
            }
            if (!empty($item['update_time'])) {
                $item['update_time'] = date('Y-m-d H:i:s', strtotime($item['update_time']));
            }

            // 添加出国时长计算（如果有完整的出返日期）
            if (!empty($item['abroad_date']) && !empty($item['return_date'])) {
                $abroad_timestamp = strtotime($item['abroad_date']);
                $return_timestamp = strtotime($item['return_date']);
                if ($return_timestamp >= $abroad_timestamp) {
                    $days = floor(($return_timestamp - $abroad_timestamp) / (24 * 3600));
                    $item['abroad_duration'] = "{$days}天";
                }
            }
        }

        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => ['resultList' => $list],
            'totalCount' => $total
        ]);
    }

    /**
     * 批量删除出国事件
     * @return \think\response\Json
     */
    public function batchDeleteAbroadEvent()
    {
        $ids = input('post.ids/a');  // 获取ID数组

        if (empty($ids)) {
            return json([
                'code' => 400,
                'message' => '请选择要删除的记录'
            ]);
        }

        try {
            // 使用软删除，将is_delete设置为'1'
            $result = Db::table('zstp_neo4j_abroad_event')
                ->whereIn('id', $ids)
                ->update(['is_delete' => '1', 'update_time' => date('Y-m-d H:i:s')]);

            if ($result) {
                $sysLogService = new SysLogService();
                $ids=implode(',', $ids);
                $result =  $sysLogService->addLog('删除出国出境记录id('. $ids.')', $ids, 3, '出国出境记录id:'.$ids);
                return json([
                    'code' => 200,
                    'message' => '删除成功',
                    'data' => [
                        'count' => $result
                    ]
                ]);
            } else {
                return json([
                    'code' => 400,
                    'message' => '删除失败'
                ]);
            }
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '删除失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 批量删除个人属性记录
     */
    public function batchDeletePersonalAttributes()
    {
        $ids = input('post.ids/a');

     
        if (empty($ids)) {
            return json(['code' => 400, 'message' => '请选择要删除的记录']);
        }

        try {
            $result = Db::table('zstp_neo4j_personal_attributes')
                ->whereIn('id', $ids)
                ->update(['is_delete' => '1', 'update_time' => date('Y-m-d H:i:s')]);

            if ($result) {
                $sysLogService = new SysLogService();

                $ids=implode(',', $ids);
        
                $result =  $sysLogService->addLog('删除人物属性id('. $ids.')', $ids, 3, '人物属性id:'.$ids);
                return json([
                    'code' => 200,
                    'message' => '删除成功',
                    'data' => ['count' => $result]
                ]);
            }


        } catch (\Exception $e) {
            return json(['code' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 批量删除组织机构记录
     */
    public function batchDeleteOrganization()
    {
        $ids = input('post.ids/a');

        if (empty($ids)) {
            return json(['code' => 400, 'message' => '请选择要删除的记录']);
        }

        try {
            $result = Db::table('zstp_neo4j_organization')
                ->whereIn('id', $ids)
                ->update(['is_delete' => '1', 'update_time' => date('Y-m-d H:i:s')]);

            if ($result) {
                $sysLogService = new SysLogService();
                $ids=implode(',', $ids);
                $result =  $sysLogService->addLog('删除组织机构属性id('. $ids.')', $ids, 3, '组织机构属性id:'.$ids);
                return json([
                    'code' => 200,
                    'message' => '删除成功',
                    'data' => ['count' => $result]
                ]);
            }


        } catch (\Exception $e) {
            return json(['code' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 批量删除重要事件记录
     */
    public function batchDeleteSignificantEvent()
    {
        $ids = input('post.ids/a');

        if (empty($ids)) {
            return json(['code' => 400, 'message' => '请选择要删除的记录']);
        }

        try {
            $result = Db::table('zstp_neo4j_significant_events')
                ->whereIn('id', $ids)
                ->update(['is_delete' => '1', 'update_time' => date('Y-m-d H:i:s')]);


            if ($result) {
                $sysLogService = new SysLogService();
                $ids=implode(',', $ids);
                $result =  $sysLogService->addLog('删除机构大事记抽取id('. $ids.')', $ids, 3, '机构大事记抽取id:'.$ids);
                return json([
                    'code' => 200,
                    'message' => '删除成功',
                    'data' => ['count' => $result]
                ]);
            }

            return json([
                'code' => 200,
                'message' => '删除成功',
                'data' => ['count' => $result]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 批量删除社会关系记录
     */
    public function batchDeleteSocialRelation()
    {
        $ids = input('post.ids/a');
        $type = input('post.type/s', '');

        if (empty($ids)) {
            return json(['code' => 400, 'message' => '请选择要删除的记录']);
        }

        try {
            $result = Db::table('zstp_neo4j_social_relations')
                ->whereIn('id', $ids)
                ->update(['is_delete' => '1', 'update_time' => date('Y-m-d H:i:s')]);

            if ($result) {
                $sysLogService = new SysLogService();
                $ids=implode(',', $ids);


                if($type == "socialrelations"){ 
                    $result =  $sysLogService->addLog('删除社会关系id('. $ids.')', $ids, 3, '社会关系id:'.$ids);
                }else{
                    $result =  $sysLogService->addLog('删除配偶子女id('. $ids.')', $ids, 3, '配偶子女id:'.$ids);
                }

               
                return json([
                    'code' => 200,
                    'message' => '删除成功',
                    'data' => ['count' => $result]
                ]);
            }

       
        } catch (\Exception $e) {
            return json(['code' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 批量删除历史演变记录
     */
    public function batchDeleteHistoricalEvolution()
    {
        $ids = input('post.ids/a');

        if (empty($ids)) {
            return json(['code' => 400, 'message' => '请选择要删除的记录']);
        }

        try {
            $result = Db::table('zstp_neo4j_historical_evolution')
                ->whereIn('id', $ids)
                ->update(['is_delete' => '1', 'update_time' => date('Y-m-d H:i:s')]);

            if ($result) {
                $sysLogService = new SysLogService();
                $ids=implode(',', $ids);
                $result =  $sysLogService->addLog('删除机构历史沿革抽取id('. $ids.')', $ids, 3, '机构历史沿革抽取id:'.$ids);
                return json([
                    'code' => 200,
                    'message' => '删除成功',
                    'data' => ['count' => $result]
                ]);
            }

            return json([
                'code' => 200,
                'message' => '删除成功',
                'data' => ['count' => $result]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 批量删除奖惩事件记录
     */
    public function batchDeleteRewardsPunishments()
    {
        $ids = input('post.ids/a');

        if (empty($ids)) {
            return json(['code' => 400, 'message' => '请选择要删除的记录']);
        }

        try {
            $result = Db::table('zstp_neo4j_rewards_punishments_event')
                ->whereIn('id', $ids)
                ->update(['is_delete' => '1', 'update_time' => date('Y-m-d H:i:s')]);

            if ($result) {
                $sysLogService = new SysLogService();
                $ids=implode(',', $ids);
    
                $result =  $sysLogService->addLog('删除奖惩抽取id('. $ids.')', $ids, 3, '奖惩抽取id:'.$ids);
                return json([
                    'code' => 200,
                    'message' => '删除成功',
                    'data' => ['count' => $result]
                ]);
            }

    
        } catch (\Exception $e) {
            return json(['code' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 批量删除职位事件记录
     */
    public function batchDeletePositionEvent()
    {
        $ids = input('post.ids/a');

        if (empty($ids)) {
            return json(['code' => 400, 'message' => '请选择要删除的记录']);
        }

        try {
            $result = Db::table('zstp_neo4j_position_event')
                ->whereIn('id', $ids)
                ->update(['is_delete' => '1', 'update_time' => date('Y-m-d H:i:s')]);

            if ($result) {
                $sysLogService = new SysLogService();
                $ids=implode(',', $ids);
                $result =  $sysLogService->addLog('任职履历id('. $ids.')', $ids, 3, '任职履历id:'.$ids);
                return json([
                    'code' => 200,
                    'message' => '删除成功',
                    'data' => ['count' => $result]
                ]);
            }

           
        } catch (\Exception $e) {
            return json(['code' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 批量删除军衔事件记录
     */
    public function batchDeleteRankEvent()
    {
        $ids = input('post.ids/a');

        if (empty($ids)) {
            return json(['code' => 400, 'message' => '请选择要删除的记录']);
        }

        try {
            $result = Db::table('zstp_neo4j_rank_event')
                ->whereIn('id', $ids)
                ->update(['is_delete' => '1', 'update_time' => date('Y-m-d H:i:s')]);

            if ($result) {
                $sysLogService = new SysLogService();
                $ids=implode(',', $ids);
                $result =  $sysLogService->addLog('删除军衔/级别id('. $ids.')', $ids, 3, '删除军衔/级别id:'.$ids);
                return json([
                    'code' => 200,
                    'message' => '删除成功',
                    'data' => ['count' => $result]
                ]);
            }


        } catch (\Exception $e) {
            return json(['code' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    public function batchDeleteQueue()
    {
        $ids = input('post.ids/a');
        if (empty($ids)) {
            return json(['code' => 400, 'msg' => '请选择要删除的记录']);
        }


        $result = Db::table('zstp_obtain_queue')->whereIn('id', $ids)->update(['is_delete' => 1, 'update_time' => date('Y-m-d H:i:s')]);

        return json(['code' => 200, 'msg' => '删除成功', 'data' => $result]);
    }

    function getmingzhongdata(){

        $data = request()->put();

        $id = $data['id'];

      
        // $dataArr=[];

        // $map['queue_id']= $data['id'];
        // $resAbroad= Db::table("zstp_neo4j_abroad_event")->where( $map)->select();
        // $dataArr['出国事件']=array();
        // if(!empty( $resAbroad)){
        //     $dataArr['出国事件']=   $resAbroad;        
        // }

        
 
        // $resAbroad= Db::table("zstp_neo4j_historical_evolution")->where( $map)->select();

        // $dataArr['组织历史变迁']=array();
        // if(!empty( $resAbroad)){
        //     $dataArr['组织历史变迁']=   $resAbroad;        
        // }



        // $resAbroad= Db::table("zstp_neo4j_organization")->where( $map)->select();

        // $dataArr['组织属性']=array();
        // if(!empty( $resAbroad)){
        //     $dataArr['组织属性']=   $resAbroad;        
        // }


        // $resAbroad= Db::table("zstp_neo4j_personal_attributes")->where( $map)->select();

        // $dataArr['个人属性']=array();
        // if(!empty( $resAbroad)){
        //     $dataArr['个人属性']=   $resAbroad;        
        // }

        // $resAbroad= Db::table("zstp_neo4j_position_event")->where( $map)->select();
        // $dataArr['职位任免']=array();
        // if(!empty( $resAbroad)){
        //     $dataArr['职位任免']=   $resAbroad;        
        // }

   
        // $resAbroad= Db::table("zstp_neo4j_rank_event")->where( $map)->select();

        // $dataArr['军衔']=array();
        
  
        // if(!empty( $resAbroad)){
        //     $dataArr['军衔']=   $resAbroad;        
        // }



        // $resAbroad= Db::table("zstp_neo4j_rewards_punishments_event")->where( $map)->select();

        // $dataArr['奖惩']=array();

        // if(!empty( $resAbroad)){
        //     $dataArr['奖惩']=   $resAbroad;        
        // }


        // $resAbroad= Db::table("zstp_neo4j_significant_events")->where( $map)->select();

        // $dataArr['组织重大事件']=array();
        // if(!empty( $resAbroad)){
        //     $dataArr['组织重大事件']=   $resAbroad;        
        // }


        // $resAbroad= Db::table("zstp_neo4j_social_relations")->where( $map)->select();

        // $dataArr['社会关系']=array();
        // if(!empty( $resAbroad)){
        //     $dataArr['社会关系']=   $resAbroad;        
        // }

        $result = Db::table('zstp_obtain_queue')->where('id', $id)->find();

        $dataArr = json_decode($result['text'], true);


        return json(['code' => 200, 'msg' => '获取成功', 'data' => $dataArr]);  
    }


     function  updatePersonalAttribute(){
        $data = request()->put();


        $update_data=[];


        if(!empty($data['name'])){
            $update_data['name']=$data['name'];
        }
        if(!empty($data['gender'])){
            $update_data['gender']=$data['gender'];
        }
        if(!empty($data['ethnicity'])){
            $update_data['ethnicity']=$data['ethnicity'];
        }
        if(!empty($data['political_status'])){
            $update_data['political_status']=$data['political_status'];
        }

        if(!empty($data['marital_status'])){
            $update_data['marital_status']=$data['marital_status'];
        }

        if(!empty($data['birth_date'])){
            $update_data['birth_date']=$data['birth_date'];
        }

        if(!empty($data['party_join_date'])){
            $update_data['party_join_date']=$data['party_join_date'];
        }

        if(!empty($data['enlistment_date'])){
            $update_data['enlistment_date']=$data['enlistment_date'];
        }

        if(!empty($data['discharge_date'])){
            $update_data['discharge_date']=$data['discharge_date'];
        }

        if(!empty($data['native_place'])){
            $update_data['native_place']=$data['native_place'];
        }

        if(!empty($data['education'])){
            $update_data['education']=$data['education'];
        }


        if(!empty($data['graduation_institution'])){
            $update_data['graduation_institution']=$data['graduation_institution'];
        }

        if(!empty($data['skills_and_expertise'])){
            $update_data['skills_and_expertise']=$data['skills_and_expertise'];
        }


         $result =  Db::table('zstp_neo4j_personal_attributes')->where('id',$data['id'])->update($update_data);

         if($result){
    
          $SysLogService   =    new SysLogService();

          $dataJson = json_encode($data ,JSON_UNESCAPED_UNICODE);

          $SysLogService->addLog("编辑人物属性 id(".$data['id'].")", $data['id'], 2, '编辑内容（'.$dataJson.'）');
            
            return json(['code' => 200, 'msg' => '更新成功']);
         }else{
            return json(['code' => 400, 'msg' => '更新失败']);
         }
        
        

     }

      function updateOrganization (){
        //获取请求参数
        $data = request()->put();

        $update_data=[];

        if(!empty($data['area_of_responsibility'])){
            $update_data['area_of_responsibility']=$data['area_of_responsibility'];
        }

        if(!empty($data['commander_name'])){
            $update_data['commander_name']=$data['commander_name'];
        }

        if(!empty($data['establishment_date'])){
            $update_data['establishment_date']=$data['establishment_date'];
        }
        if(!empty($data['location'])){
            $update_data['location']=$data['location'];
        }

        if(!empty($data['note'])){
            $update_data['note']=$data['note'];
        }
        if(!empty($data['parent_unit_name'])){
            $update_data['parent_unit_name']=$data['parent_unit_name'];
        }

        if(!empty($data['specialization'])){
            $update_data['specialization']=$data['specialization'];
        }

        if(!empty($data['strength'])){
            $update_data['strength']=$data['strength'];
        }

        if(!empty($data['unit_designation'])){
            $update_data['unit_designation']=$data['unit_designation'];
        }

        if(!empty($data['unit_name'])){
            $update_data['unit_name']=$data['unit_name'];
        }
        
        if(!empty($data['unit_type'])){
            $update_data['unit_type']=$data['unit_type'];
        }

        $result = Db::table('zstp_neo4j_organization')->where('id',$data['id'])->update($update_data);

        if($result){
            $SysLogService   =    new SysLogService();

            $dataJson = json_encode($data ,JSON_UNESCAPED_UNICODE);

            $SysLogService->addLog("编辑组织机构属性 id(".$data['id'].")", $data['id'], 2, '编辑内容（'.$dataJson.'）');

            return json(['code' => 200, 'msg' => '更新成功']);
        }else{
            return json(['code' => 400, 'msg' => '更新失败']);
        }



     }

     function updaterewardspunishment(){
        $data = request()->put();
        $update_data=[];
        
        if(!empty($data['event_date'])){
            $update_data['event_date']=$data['event_date'];
        }

        if(!empty($data['event_type'])){
            $update_data['event_type']=$data['event_type'];
        }

        if(!empty($data['issuer'])){
            $update_data['issuer']=$data['issuer'];
        }

        if(!empty($data['reason'])){
            $update_data['reason']=$data['reason'];
        }

        if(!empty($data['subject_name'])){
            $update_data['subject_name']=$data['subject_name'];
        }

        if(!empty($data['summary'])){
            $update_data['summary']=$data['summary'];
        }


       $result = Db::table('zstp_neo4j_rewards_punishments_event')->where('id',$data['id'])->update($update_data);

        if($result){
            $SysLogService   =    new SysLogService();
            $dataJson = json_encode($data ,JSON_UNESCAPED_UNICODE);

            $SysLogService->addLog("编辑奖惩抽 id(".$data['id'].")", $data['id'], 2, '编辑内容（'.$dataJson.'）');

            return json(['code' => 200, 'msg' => '更新成功']);
        }else{
            return json(['code' => 400, 'msg' => '更新失败']);
        }

       
        
    
     }

     function updatePositionEvent(){
        $data = request()->put();
        $update_data=[];
        
        if(!empty($data['current_position'])){
            $update_data['current_position']=$data['current_position'];
        }

        if(!empty($data['department'])){
            $update_data['department']=$data['department'];
        }

        if(!empty($data['effective_date'])){
            $update_data['effective_date']=$data['effective_date'];
        }

        if(!empty($data['event_date'])){
            $update_data['event_date']=$data['event_date'];

        }

        if(!empty($data['event_type'])){
            $update_data['event_type']=$data['event_type'];
        }

        if(!empty($data['issuer'])){
            $update_data['issuer']=$data['issuer'];
        }

        if(!empty($data['original_position'])){
            $update_data['original_position']=$data['original_position'];
        }

        if(!empty($data['personnel_name'])){
            $update_data['personnel_name']=$data['personnel_name'];
        }

        if(!empty($data['summaposition_changery'])){
            $update_data['position_change']=$data['position_change'];
        }

        if(!empty($data['reason'])){
            $update_data['reason']=$data['reason'];
        }

        
        
        $result = Db::table('zstp_neo4j_position_event')->where('id',$data['id'])->update($update_data);

        if($result){
            $SysLogService   =    new SysLogService();
            $dataJson = json_encode($data ,JSON_UNESCAPED_UNICODE);

            $SysLogService->addLog("编辑任职履历 id(".$data['id'].")", $data['id'], 2, '编辑内容（'.$dataJson.'）');

            return json(['code' => 200, 'msg' => '更新成功']);
        }else{
            return json(['code' => 400, 'msg' => '更新失败']);
        }

        
        
     }


     function updateRankEvent(){
        $data = request()->put();
        $update_data=[];

        

        if(!empty($data['current_position'])){
            $update_data['current_position']=$data['current_position'];
        }
        
        if(!empty($data['department'])){
            $update_data['department']=$data['department'];
        }

        if(!empty($data['effective_date'])){
            $update_data['effective_date']=$data['effective_date'];
        }
        
        if(!empty($data['event_date'])){
            $update_data['event_date']=$data['event_date'];
        }

        if(!empty($data['event_type'])){
            $update_data['event_type']=$data['event_type'];
        }

        if(!empty($data['issuer'])){
            $update_data['issuer']=$data['issuer'];
        }
        


        if(!empty($data['personnel_name'])){
            $update_data['personnel_name']=$data['personnel_name'];
        }

        if(!empty($data['position'])){
            $update_data['position']=$data['position'];
        }

        if(!empty($data['original_position'])){
            $update_data['original_position']=$data['original_position'];
        }

        if(!empty($data['rank_change'])){
            $update_data['rank_change']=$data['rank_change'];
        }
        
        
        if(!empty($data['reason'])){
            $update_data['reason']=$data['reason'];
        }

        if(!empty($data['summary'])){
            $update_data['summary']=$data['summary'];
        }
        
        $result = Db::table('zstp_neo4j_rank_event')->where('id',$data['id'])->update($update_data);

        if($result){    
            $SysLogService   =    new SysLogService();
            $dataJson = json_encode($data ,JSON_UNESCAPED_UNICODE);

            $SysLogService->addLog("编辑军衔/级别 id(".$data['id'].")", $data['id'], 2, '编辑内容（'.$dataJson.'）');

            return json(['code' => 200, 'msg' => '更新成功']);

        }else{
            return json(['code' => 400, 'msg' => '更新失败']);
        }

        
        
        
        
     }
     
     function updateabroadevent(){
        $data = request()->put();
        $update_data=[];

        if(!empty($data['abroad_date'])){
            $update_data['abroad_date']=$data['abroad_date'];
        }

        if(!empty($data['return_date'])){
            $update_data['return_date']=$data['return_date'];
        }

        if(!empty($data['personnel_name'])){
            $update_data['personnel_name']=$data['personnel_name'];

        }

        if(!empty($data['country'])){
            $update_data['country']=$data['country'];
        }

        if(!empty($data['reason'])){
            $update_data['reason']=$data['reason'];
        }

        $result = Db::table('zstp_neo4j_abroad_event')->where('id',$data['id'])->update($update_data);

        if($result){
            $SysLogService   =    new SysLogService();
            $dataJson = json_encode($data ,JSON_UNESCAPED_UNICODE);

            $SysLogService->addLog("编辑出国出境 id(".$data['id'].")", $data['id'], 2, '编辑内容（'.$dataJson.'）');

            return json(['code' => 200, 'msg' => '更新成功']);

        }else{
            return json(['code' => 400, 'msg' => '更新失败']);
        }
        
        
     }


     public function updatesocialrelation(){
        $data = request()->put();
        $update_data=[];

        if(!empty($data['birth_date'])){
            $update_data['birth_date']=$data['birth_date'];
        }

        if(!empty($data['discharge_date'])){
            $update_data['discharge_date']=$data['discharge_date'];
        }

        if(!empty($data['education'])){
            $update_data['education']=$data['education'];
        }

        if(!empty($data['enlistment_date'])){
            $update_data['enlistment_date']=$data['enlistment_date'];
        }

        if(!empty($data['ethnicity'])){
            $update_data['ethnicity']=$data['ethnicity'];
        }

        if(!empty($data['gender'])){
            $update_data['gender']=$data['gender'];
        }

        if(!empty($data['graduation_institution'])){
            $update_data['graduation_institution']=$data['graduation_institution'];
        }

        if(!empty($data['linked_person_name'])){
            $update_data['linked_person_name']=$data['linked_person_name'];
        }

        if(!empty($data['marital_status'])){
            $update_data['marital_status']=$data['marital_status'];
        }

        if(!empty($data['marriage_date'])){
            $update_data['marriage_date']=$data['marriage_date'];
        }

        if(!empty($data['name'])){
            $update_data['name']=$data['name'];
        }

        if(!empty($data['native_place'])){
            $update_data['native_place']=$data['native_place'];
        }

        if(!empty($data['note'])){
            $update_data['note']=$data['note'];
        }

        if(!empty($data['occupation'])){
            $update_data['occupation']=$data['occupation'];
        }

        if(!empty($data['party_join_date'])){
            $update_data['party_join_date']=$data['party_join_date'];
        }

        if(!empty($data['political_status'])){
            $update_data['political_status']=$data['political_status'];
        }

        if(!empty($data['relationship_type'])){
            $update_data['relationship_type']=$data['relationship_type'];
        }

        if(!empty($data['skills_and_expertise'])){
            $update_data['skills_and_expertise']=$data['skills_and_expertise'];
        }
        
        if(!empty($data['with_army'])){
            $update_data['with_army']=$data['with_army'];
        }

        if(!empty($data['workplace'])){
            $update_data['workplace']=$data['workplace'];
        }

        $result = Db::table('zstp_neo4j_social_relations')->where('id',$data['id'])->update($update_data);

        if($result){
            $SysLogService   =    new SysLogService();
            $dataJson = json_encode($data ,JSON_UNESCAPED_UNICODE);

            if($data['type'] == "socialrelations"){
                $SysLogService->addLog("编辑社会关系 id(".$data['id'].")", $data['id'], 2, '编辑内容（'.$dataJson.'）');
            }else{
                $SysLogService->addLog("编辑配偶子女 id(".$data['id'].")", $data['id'], 2, '编辑内容（'.$dataJson.'）');
            }

            

            return json(['code' => 200, 'msg' => '更新成功']);

        }else{
            return json(['code' => 400, 'msg' => '更新失败']);
        }


        
    }  
    
    public function updatehistoricalevolution(){
        $data = request()->put();
        $update_data=[];

        if(!empty($data['after_change'])){
            $update_data['after_change']=$data['after_change'];
        }

        if(!empty($data['before_change'])){
            $update_data['before_change']=$data['before_change'];
        }

        if(!empty($data['change_date'])){
            $update_data['change_date']=$data['change_date'];
        }

        if(!empty($data['change_type'])){
            $update_data['change_type']=$data['change_type'];
        }

        if(!empty($data['commander_name'])){
            $update_data['commander_name']=$data['commander_name'];
        }

        if(!empty($data['former_commander_name'])){
            $update_data['former_commander_name']=$data['former_commander_name'];
        }

        if(!empty($data['note'])){
            $update_data['note']=$data['note'];
        }

        if(!empty($data['reason'])){
            $update_data['reason']=$data['reason'];
        }

        if(!empty($data['unit_name'])){
            $update_data['unit_name']=$data['unit_name'];
        }

       $result = Db::table('zstp_neo4j_historical_evolution')->where('id',$data['id'])->update($update_data);

       if($result){
        $SysLogService   =    new SysLogService();
        $dataJson = json_encode($data ,JSON_UNESCAPED_UNICODE);
   
        $SysLogService->addLog("编辑机构历史沿革 id(".$data['id'].")", $data['id'], 2, '编辑内容（'.$dataJson.'）');

        return json(['code' => 200, 'msg' => '更新成功']);

       }else{
        return json(['code' => 400, 'msg' => '更新失败']);
       }

    }

    public function updatesignificantevent(){
        $data = request()->put();
        $update_data=[];

        if(!empty($data['description'])){
            $update_data['description']=$data['description'];
        }

        if(!empty($data['event_date'])){
            $update_data['event_date']=$data['event_date'];
        }

        if(!empty($data['event_title'])){
            $update_data['event_title']=$data['event_title'];
        }

        if(!empty($data['impact'])){
            $update_data['impact']=$data['impact'];
        }

        if(!empty($data['location'])){
            $update_data['location']=$data['location'];
        }

        if(!empty($data['note'])){
            $update_data['note']=$data['note'];
        }

        if(!empty($data['participants'])){
            $update_data['participants']=$data['participants'];
        }

        if(!empty($data['type'])){
            $update_data['type']=$data['type'];
        }

        if(!empty($data['unit_name'])){
            $update_data['unit_name']=$data['unit_name'];
        }



        $result = Db::table('zstp_neo4j_significant_events')->where('id',$data['id'])->update($update_data);

        if($result){
            $SysLogService   =    new SysLogService();
            $dataJson = json_encode($data ,JSON_UNESCAPED_UNICODE);

            $SysLogService->addLog("编辑机构大事记 id(".$data['id'].")", $data['id'], 2, '编辑内容（'.$dataJson.'）');

            return json(['code' => 200, 'msg' => '更新成功']);

        }else{
            return json(['code' => 400, 'msg' => '更新失败']);
        }


        return json(['code' => 200, 'msg' => '更新成功']);
        
    
    }

    function getRewardsList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $event_type = input('event_type/s', '');
        $subject_name = input('subject_name/s', '');
        $issuer = input('issuer/s', '');
        $event_date_start = input('event_date_start/s', '');
        $event_date_end = input('event_date_end/s', '');
        $article_id = input('article_id/d', '');

        $where = ['is_delete' => '0'];

        if ($event_type !== '') {
            $where['event_type'] = ['like', "%{$event_type}%"];
        }
        if ($subject_name !== '') {
            $where['subject_name'] = ['like', "%{$subject_name}%"];
        }
        if ($issuer !== '') {
            $where['issuer'] = ['like', "%{$issuer}%"];
        }
        if ($article_id !== '') {
            $where['article_id'] = $article_id;
        }

        // 日期范围查询
        if ($event_date_start !== '' && $event_date_end !== '') {
            $where['event_date'] = ['between', [$event_date_start, $event_date_end]];
        } else if ($event_date_start !== '') {
            $where['event_date'] = ['>=', $event_date_start];
        } else if ($event_date_end !== '') {
            $where['event_date'] = ['<=', $event_date_end];
        }

        $total = db('zstp_neo4j_rewards')->where($where)->count();
        $list = db('zstp_neo4j_rewards')
            ->where($where)
            ->page($page, $limit)
            ->order('event_date desc, id desc')
            ->select();

      


        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => ['resultList' => $list],
            'totalCount' => $total
        ]);
    }


    public function updateRewards(){
        $data = request()->put();
        $update_data=[];
        
        if(!empty($data['issuer'])){
            $update_data['issuer']=$data['issuer'];
        }

        if(!empty($data['project_name'])){
            $update_data['project_name']=$data['project_name'];
        }

        if(!empty($data['ranking'])){
            $update_data['ranking']=$data['ranking'];
        }

        if(!empty($data['reason'])){
            $update_data['reason']=$data['reason'];
        }

        if(!empty($data['reward_name'])){
            $update_data['reward_name']=$data['reward_name'];
        }

        if(!empty($data['subject_name'])){
            $update_data['subject_name']=$data['subject_name'];
        }
          if(!empty($data['event_date'])){
            $update_data['event_date']=$data['event_date'];
        }


       $result = Db::table('zstp_neo4j_rewards')->where('id',$data['id'])->update($update_data);

        if($result){
            $SysLogService   =    new SysLogService();
            $dataJson = json_encode($data ,JSON_UNESCAPED_UNICODE);
            $SysLogService->addLog("编辑科技奖励 id(".$data['id'].")", $data['id'], 2, '编辑内容（'.$dataJson.'）');
            return json(['code' => 200, 'msg' => '更新成功']);
        }else{
            return json(['code' => 400, 'msg' => '更新失败']);
        }

    }

       /**
     * 批量删除奖惩事件记录
     */
    public function batchDeleteRewards()
    {
        $ids = input('post.ids/a');

        if (empty($ids)) {
            return json(['code' => 400, 'message' => '请选择要删除的记录']);
        }

        try {
            $result = Db::table('zstp_neo4j_rewards')
                ->whereIn('id', $ids)
                ->update(['is_delete' => '1', 'update_time' => date('Y-m-d H:i:s')]);

            if ($result) {
                $sysLogService = new SysLogService();
                $ids=implode(',', $ids);
    
                $result =  $sysLogService->addLog('删除科技奖励id('. $ids.')', $ids, 3, '科技奖励抽取id:'.$ids);
                return json([
                    'code' => 200,
                    'message' => '删除成功',
                    'data' => ['count' => $result]
                ]);
            }

    
        } catch (\Exception $e) {
            return json(['code' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    function getSpousechildrenList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $name = input('name/s', '');
        $linked_person_name = input('linked_person_name/s', '');
        $relationship_type = input('relationship_type/s', '');
        $gender = input('gender/s', '');
        $political_status = input('political_status/s', '');
        $workplace = input('workplace/s', '');
        $article_id = input('article_id/d', '');

        $where = ['is_delete' => '0'];

        if ($name !== '') {
            $where['name'] = ['like', "%{$name}%"];
        }
        if ($linked_person_name !== '') {
            $where['linked_person_name'] = ['like', "%{$linked_person_name}%"];
        }
        if ($relationship_type !== '') {
            $where['relationship_type'] = ['like', "%{$relationship_type}%"];
        }
        if ($gender !== '') {
            $where['gender'] = $gender;
        }
        if ($political_status !== '') {
            $where['political_status'] = ['like', "%{$political_status}%"];
        }
        if ($workplace !== '') {
            $where['workplace'] = ['like', "%{$workplace}%"];
        }
        if ($article_id !== '') {
            $where['article_id'] = $article_id;
        }


        //社会关系

        $where['relationship_type'] = array(  "in",array("女儿","儿子","配偶"));

        $total = Db::table('zstp_neo4j_social_relations')
            ->where($where)
            ->count();

        $list = Db::table('zstp_neo4j_social_relations')

            ->where($where)
            ->page($page, $limit)
            ->order('id desc')
            ->select();

        // 格式化日期显示
        foreach ($list as &$item) {
            if (!empty($item['birth_date'])) {
                $item['birth_date'] = date('Y-m-d', strtotime($item['birth_date']));
            }
            if (!empty($item['create_time'])) {
                $item['create_time'] = date('Y-m-d H:i:s', strtotime($item['create_time']));
            }
            if (!empty($item['update_time'])) {
                $item['update_time'] = date('Y-m-d H:i:s', strtotime($item['update_time']));
            }
        }

        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => ['resultList' => $list],
            'totalCount' => $total
        ]);
    }

    
     
    
}
